package com.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.pms.entity.Mind;
import com.pms.entity.User;
import com.pms.util.DBHelp;
import com.pms.util.Page;
import com.pms.util.RowMapper;

public class MindDao {
	private DBHelp<Mind> db=new DBHelp<Mind>();
	
	public Long getCount(String projectId){
		String sql="select count(*) from t_mind where projectid=?";
		return (Long)db.executeQueryForFunction(sql,projectId);
	}
	public void save(Mind mind){
		String sql="INSERT INTO t_mind(mindid,`desc`,createtime,userid,projectid) VALUES(?,?,?,?,?)";
		db.executeSQL(sql, mind.getMindId(),mind.getDesc(),mind.getCreateTime(),mind.getUserId(),mind.getProjectId());
	}
	
	public Page<Mind> findAll(String projectId,Page<Mind> page){
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tm.mindid,tm.desc,tm.createtime,tm.userid,tm.projectid,tu.username,tu.password,tu.nickname,tu.picture FROM t_mind AS tm ");
		sql.append("LEFT JOIN t_user AS tu ON tm.userid=tu.userid ");
		sql.append("WHERE tm.projectid=? order by tm.createtime desc limit ?,?");
		List<Mind> list=db.executeQueryForList(sql.toString(), new MindRowMapper(), projectId,page.getOffSet(),page.getPageSize());
		page.setResult(list);
		return page;
	}
	
	
	public class MindRowMapper implements RowMapper<Mind>{

		public Mind mapRow(ResultSet rs) throws SQLException {
			
			Mind mind=new Mind();
			User user=new User();
			user.setUserId(rs.getString("userId"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			user.setNickName(rs.getString("nickName"));
			user.setPicture(rs.getString("picture"));
			mind.setUser(user);
			
			mind.setMindId(rs.getString("mindId"));
			mind.setDesc(rs.getString("desc"));
			mind.setCreateTime(rs.getString("createTime"));
			mind.setUserId(rs.getString("userId"));
			mind.setProjectId(rs.getString("projectId"));
			return mind;
		}
		
	}

}
